var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var user = require('../../../utils/user.js');

var app = getApp();
Page({
  data: {
    canIUseGetUserProfile: false,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  wxLogin: function (e) {
    wx.showLoading({
      title: '登录中...',
    });
    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.doLogin(res.userInfo)
        },
        fail: () => {
          util.showErrorToast('微信登录失败');
          wx.hideLoading();
        }
      })
    } else {
      if (e.detail.userInfo == undefined) {
        app.globalData.hasLogin = false;
        util.showErrorToast('微信登录失败');
        wx.hideLoading();
        return;
      }
      this.doLogin(e.detail.userInfo)
    }
  },
  doLogin: function (userInfo) {
    let that = this;
    user.checkLogin().catch(() => {
      user.loginByWeixin(userInfo).then(res => {
        app.globalData.hasLogin = true;
        wx.hideLoading();
        // wx.navigateBack({
        //   delta: 1
        // })
        that.checkShopInfo();
      }).catch((err) => {
        wx.hideLoading();
        app.globalData.hasLogin = false;
        util.showErrorToast('微信登录失败');
      });

    });
  },
  accountLogin: function () {
    wx.navigateTo({
      url: "/pages/auth/accountLogin/accountLogin"
    });
  },
  /**
   * 用户认证信息检查{未认证用户：跳转到商户认证界面，已认证用户跳转到首页}
   */
  checkShopInfo: function () {
    let shopInfo = wx.getStorageSync('shopInfo');
    if (shopInfo) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    } else {
      wx.showLoading({
        title: '加载中...',
      });
      util.request(api.CouuntTargetStatus, {
        status: 0
      }).then(function (res) {
        wx.hideLoading();
        if (res.errno === 0) {
          if (res.data > 0) {
            wx.reLaunch({
              url: "/pages/auth/authenticationIdentityWait/authenticationIdentityWait"
            });
          } else {
            wx.reLaunch({
              url: "/pages/auth/authenticationIdentity/authenticationIdentity"
            });
          }
        }
      });
    }
  },
})